import { Form, Input, Button, Checkbox, Row, Col, Radio, Space, Modal } from 'antd';
import Address from '../../components/Account/Address'
import { useRouter } from 'next/router';
import { useEffect,useContext,useState } from "react";
import { PlusOutlined } from '@ant-design/icons';
import Meta from "../../components/Meta";
import Header from "../../components/Header/Header";
import { request } from "../../utils/request";
import { basePath } from '../../utils/tool';
import { AppContext } from "../../store";
import PayPalCheckoutButton from '../../components/Paypal/PayPalCheckoutButton';
export default function checkout(props) {
  console.log('process.env1', process.env.APIURL)
  const { dispatch } = useContext(AppContext);
  const router = useRouter();
  const [form] = Form.useForm()
  const [cartData, setCart] = useState([])
  const [addrList, setList] = useState([])
  const [total, setTotal] = useState(0);
  const [visible ,setShow] = useState(false);
  const [addrData,setAddrData] = useState({})
  const [totalQty,setTotalQty] = useState(0);
  const [addId,setId] = useState(null);
  const [loading,setLoading] = useState(false);
  const [showPayBtn,setShowPayBtn] = useState(false);
  const [units,setUnits] = useState([])
  const [orderNo,setOrderNo] = useState(null)
  const [shippingFee,setShippingFee] = useState(0)
  const [totalAmount,setTotalAmount] = useState(0)
  const getAddrList = async () => {

    const ret = await request(`${basePath()}/api/user/shipaddrlist`);
    if (ret.code === 100000) {
      console.log('ret.data', ret.data)
      setList(ret.data)
    } else {
      message.error('get Shipping address list error')
    }
  }
  const editAddr = ()=>{
    getAddrList();
    setShow(false)
  }
  useEffect(() => {
    const list = JSON.parse(localStorage.getItem('cartData'));
    const total = list.reduce((a, b) => {
      return parseFloat(a) + parseFloat(b.totalAmount)
    }, 0)
    const totalQty = list.reduce((a, b) => {
      return parseInt(a) + parseInt(b.qty)
    }, 0)
    const shipFee = localStorage.getItem('shipFee');
    setShippingFee(shipFee)
    console.log('totalQty',totalQty)
    console.log('total',total)
    setTotal(total)
    setTotalAmount((parseFloat(total)+parseFloat(shipFee)).toFixed(2))
    setTotalQty(totalQty)
    getAddrList()
    setCart(list)
  }, [])

  const onFinish = async (values) => {
    console.log('Success:', values);
    console.log('list',cartData)
    console.log('totalamount',totalAmount)
    setLoading(true)
    const ret = await request(`${basePath()}/api/order/create`,{
      goods:cartData,
      payAmount:totalAmount,
      shipAmount:shippingFee,
      totalQty,
      ...values
    });
    const addrData = addrList.find(item=>item.id === values.addressId)
    console.log('addrdata',addrData)
    if(ret.code === 100000){
      const obj = {
        amount:{
          value:totalAmount,
          currency_code:"USD",
          breakdown:{
            item_total:{
              currency_code:"USD",
              value:totalAmount
            }
          }
        },
        items:[],
        shipping_address:{
          "recipient_name": addrData.firstName+addrData.lastName,
          "line1": "",
          "line2": "",
          "city": addrData.cityName,
          "country_code": "US",
          "postal_code": addrData.zipCode,
          "phone": addrData.phone,
          "state": addrData.stateCode
        },
      }
      cartData.forEach(item=>{
        obj.items.push({
          unit_amount:{
            currency_code:"USD",
            value:item.price,
          },
          quantity:item.qty,
          name:`${item.productName +'-'+item.sizeName + '-'+item.colorEnName}`
        })
      })
      obj.items.push({
        unit_amount:{
          currency_code:"USD",
          value:shippingFee,
        },
        quantity:1,
        name:`shipping cost`
      })
      console.log('obj',obj)
      setUnits([obj])
      setOrderNo(ret.data.orderNo)
      setShowPayBtn(true)
    }
    setLoading(false)
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const openAddressModal = (e, data) => {
    console.log('data',data)
    setAddrData(data)
    setShow(true)
    e.stopPropagation()
    e.preventDefault()
    
  }
  const handleOk = ()=>{

  }
  const handleCancel = ()=>{

  }
  const changeRadio = (e)=>{
    console.log('e',e)
    setId(e.target.value)
  }
  function onChange(e) {
    console.log(`checked = ${e.target.checked}`);
   
  }
  return (
    <>
      <Meta>
        <title>NINAMOKA-checkout</title>
      </Meta>
      <Header />
      <Row>
        <Col xs={0} md={4}></Col>
        <Col className="shop-checkout" xs={24} md={16}>
          <Row>
            {/* 左 */}

            <Col xs={24} md={14}>
              <div className='checkout-left'>
                <span className='titile'>Contact information</span>
                <Form
                  labelCol={{ span: 24 }}
                  wrapperCol={{ span: 16 }}
                  onFinish={onFinish}
                  onFinishFailed={onFinishFailed}
                  autoComplete="off"
                  form={form}
                >
                  <Form.Item
                    label="Email address (for order notification)"
                    name="mail"
                    rules={[{ required: true, message: 'Please enter your email!' }]}
                  >
                    <Input />
                  </Form.Item>
                  {/* <Form.Item name="subscribe">
                    <Checkbox onChange={onChange}>Sign me up for Ninamoka emails (you can unsubscribe at any time). See our privacy policy for details.</Checkbox>
                  </Form.Item> */}
                  <Form.Item
                    label="Shipping Address"
                    name="addressId"
                    rules={[{ required: true, message: 'Please Select Address' }]}
                  >
                    <Radio.Group>
                      <Space direction="vertical">
                        {
                          addrList.length && addrList.map(item => {
                            return <Radio key={item.id} value={item.id}>
                              <div style={{ fontWeight: 'bold', fontSize: '16px', display: 'flex' }}>
                                {item.firstName + ' ' + item.lastName}
                                <span onClick={(e) => openAddressModal(e, item)} style={{ paddingLeft: '10px', textDecoration: 'underline' }}>Edit</span>
                              </div>
                              <div>
                                {item.address}, {item.cityName},{item.stateName}
                              </div>
                              <div>
                                {item.phone}
                              </div>
                            </Radio>
                          })
                        }

                      </Space>
                    </Radio.Group>
                    
                    
                    
                  </Form.Item>
                  <Form.Item style={{marginTop:'10px'}}>
                    <Button icon={<PlusOutlined />} onClick={(e) => openAddressModal(e)}>Add a Shipping address</Button>
                  </Form.Item>
                  { !showPayBtn && <Form.Item style={{marginTop:'20px'}}>
                    <Button htmlType='submit' type='primary' loading={loading}>Next Step</Button>
                  </Form.Item>}
                </Form>
              { showPayBtn && <div style={{marginTop:'30px'}}><PayPalCheckoutButton units={units} orderNo={orderNo}/></div>}
              </div>
              <div className='checkout-address'>
                {/* <span className="checkout-add">Shipping address</span> */}


              </div>
            </Col>


            {/* 右 */}
            <Col xs={24} md={10}>
              <div className='checkout-right'>
                <span className='titile'>Order summary</span>
                <div className='items'>
                  <div>
                    <span>{cartData.length} items</span>
                  </div>
                  <span>$ {total}</span>
                </div>
                {
                  cartData.map(item => {
                    return (
                      <div className='open' key={item.cartId}>
                        < img className='open-img' src={item.goodsUrl}></img>
                        <div className='open-right'>
                          <span>{item.productName}</span>
                          <span>{item.productSubName}</span>
                          <span>Color {item.colorEnName}</span>
                          <span>Size {item.sizeName}</span>
                          <div className='sub'>
                            <span>Quantity {item.qty}</span>
                            <span>$ {item.price}</span>
                          </div>
                        </div>
                      </div>
                    )
                  })
                }

                <div className=''></div>
                <div className='sub'>
                  <span>Subtotal</span>
                  <span>$ {total}</span>
                </div>
                <div className='sub'>
                  <span>Shipping</span>
                  <span>${shippingFee}</span>
                </div>
                <div className='order'>
                  <span>Order total</span>
                  <span>USD {totalAmount}</span>
                </div>
              </div>

            </Col>
          </Row>
        </Col>
        <Col xs={0} md={4}></Col>
      </Row>
      <Modal title="Edit Address" visible={visible} onOk={handleOk} onCancel={()=>setShow(false)} footer={null}>
       <Address data={addrData} handleSave={editAddr} showForm={true}/>
      </Modal>
    </>
  )
}
